﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DataMongo;
using DataMongo.Entities;
using Google.GData.Contacts;
using MongoDB.Bson;

using MVCMongo.Services;
using WebMatrix.WebData;

namespace MVCMongo.Controllers
{
    public class WallPostController : ApiController
    {


        // GET api/WallPost
        public dynamic GetPosts(int postType)
        {

            var connection = new RepositoryBaseMongo("UserPost");
            var pc = new RepositoryBaseMongo("PostComment");
            var friendlistconnection = new RepositoryBaseMongo("FriendList");
            var userconnection = new RepositoryBaseMongo("Users");
            var feedimageconnection = new RepositoryBaseMongo("FeedSourceDetail");
            var groupconnection = new RepositoryBaseMongo("Group");
            var albumconnection = new RepositoryBaseMongo("Album");
            var photoconnection = new RepositoryBaseMongo("Photos");
            var userid = WebSecurity.GetUserId(WebSecurity.CurrentUserName);
      

            if (postType == 1)
            {

                var ret = (from post in connection.GetAll<Post>().Where(x => x.PostedBy == userid).OrderByDescending(x => x.PostedDate)
                           join userimage in userconnection.GetAll<Users>().ToList() on post.PostedBy equals userimage.UserId
                           join feedimage in feedimageconnection.GetAll<FeedSourceDetail>().ToList() on post.PostId equals feedimage.UserPostId into fi
                           from ft in fi.DefaultIfEmpty()
                           join Gr in groupconnection.GetAll<Group>().ToList() on post.GroupId equals Gr.GroupId into gri
                           from grt in gri.DefaultIfEmpty()
                           select new
                          {
                              Message = post.Message,
                              PostedBy = post.PostedBy,
                              PostedByName = UtilityService.GetCurrentUserFullName(post.PostedBy),
                              PostedByAvatar = "/Content/UserProfile/User/" + userimage.ImageUrl,
                              PostedDate = post.PostedDate,
                              PostId = post.PostId,
                              LikeCount = post.LikeCount,
                              StatusHeader = post.Source,
                              AlbumImage = post.Source == "added a new Photo" ? (from n in photoconnection.GetAll<Photos>().Where(x=>x.AlbumId==post.AlbumId).OrderByDescending(x=>x.PhotoId)
                                          join a in albumconnection.GetAll<Album>().Where(x => x.UserId == userid) on n.AlbumId equals a.AlbumId
                                          select "/Content/UserProfile/UserUploadedPic/Albums/"+n.AlbumId+"/"+n.PhotoUrl).Take(post.NoOfPhotoUpload).ToList(): new List<string>(),
                             LinkThumbnailUrl = ft == null ? "" : ft.Embed,
                              Groupid = grt == null ? "" : "   >   " + UtilityService.GetGroupNamebyId(grt.GroupId),
                              PostComments = (from comment in pc.GetAll<PostComment>()
                                              join userimagecomment in userconnection.GetAll<Users>().ToList() on comment.CommentedBy equals userimagecomment.UserId

                                              where comment.PostId == post.PostId
                                              orderby comment.CommentedDate
                                              select new
                                              {
                                                  CommentedBy = comment.CommentedBy,
                                                  CommentedByName = UtilityService.GetCurrentUserFullName(comment.CommentedBy),
                                                  CommentedByAvatar = "/Content/UserProfile/User/" + userimagecomment.ImageUrl,
                                                  CommentedDate = comment.CommentedDate,
                                                  CommentId = comment.CommentId,
                                                  Message = comment.Message,
                                                  PostId = comment.PostId



                                              })
                          }).AsEnumerable();
                return ret;
            }
            else
            {
                var friendlist =
                    friendlistconnection.GetAll<FriendList>()
                        .Where(x => x.MyId == WebSecurity.GetUserId(WebSecurity.CurrentUserName)).Select(x => x.FriendId);
                var secondlist = friendlistconnection.GetAll<FriendList>()
                        .Where(x => x.FriendId == WebSecurity.GetUserId(WebSecurity.CurrentUserName)).Select(x => x.MyId);

                var ret = (from post in connection.GetAll<Post>()
                           join userimage in userconnection.GetAll<Users>().ToList() on post.PostedBy equals userimage.UserId
                           join feedimage in feedimageconnection.GetAll<FeedSourceDetail>().ToList() on post.PostId equals feedimage.UserPostId into fi
                           from ft in fi.DefaultIfEmpty()
                           where friendlist.Contains(post.PostedBy) || secondlist.Contains(post.PostedBy)
                           orderby post.PostedDate descending
                           select new
                           {
                               Message = post.Message,
                               PostedBy = post.PostedBy,
                               PostedByName = UtilityService.GetCurrentUserFullName(post.PostedBy),
                               PostedByAvatar = "/Content/UserProfile/User/" + userimage.ImageUrl,
                               PostedDate = post.PostedDate,
                               PostId = post.PostId,
                               LikeCount = post.LikeCount,
                               StatusHeader = post.Source,
                               AlbumImage = post.Source == "added a new Photo" ? (from n in photoconnection.GetAll<Photos>().Where(x => x.AlbumId == post.AlbumId).OrderByDescending(x => x.PhotoId)
                                                                                  join a in albumconnection.GetAll<Album>().Where(x => UtilityService.GetFriendList(userid).Contains(x.UserId)) on n.AlbumId equals a.AlbumId
                                                                                  select "/Content/UserProfile/UserUploadedPic/Albums/" + n.AlbumId + "/" + n.PhotoUrl).Take(post.NoOfPhotoUpload).ToList() : new List<string>(),
                               LinkThumbnailUrl = ft == null ? "" : ft.Embed,
                               PostComments = (from comment in pc.GetAll<PostComment>()
                                               join userimagecomment in userconnection.GetAll<Users>().ToList() on comment.CommentedBy equals userimagecomment.UserId
                                               where comment.PostId == post.PostId
                                               orderby comment.CommentedDate
                                               select new
                                               {
                                                   CommentedBy = comment.CommentedBy,
                                                   CommentedByName = UtilityService.GetCurrentUserFullName(comment.CommentedBy),
                                                   CommentedByAvatar = "/Content/UserProfile/User/" + userimagecomment.ImageUrl,
                                                   CommentedDate = comment.CommentedDate,
                                                   CommentId = comment.CommentId,
                                                   Message = comment.Message,
                                                   PostId = comment.PostId

                                               })
                           }).AsEnumerable();
                return ret;
            }


        }


        /*
        public Post GetPost(ObjectId _id)
        {
            var connection = new RepositoryBaseMongo("UserPost");

            var post = connection.Find<Post>(_id);
            if (post == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return post;
        }
        */


        public HttpResponseMessage PutPost(int id, Post post)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != post.PostId)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // POST api/WallPost
        public HttpResponseMessage PostPost(PostViewModel postViewModel)
        {


            var connection = new RepositoryBaseMongo("UserPost");

            int Id = 0;
            var sources = connection.GetAll<Post>().ToList();
            if (sources.Any())
                Id = sources.Max(x => x.PostId);
            Id += 1;
            postViewModel.Post.PostedBy = WebSecurity.GetUserId(WebSecurity.CurrentUserName);
            postViewModel.Post.PostedDate = DateTime.UtcNow;
            postViewModel.Post.PostId = Id;
            if (postViewModel.Source == "share this")
                postViewModel.Post.Source = postViewModel.Source;
            else
            {
                postViewModel.Post.Source = "";
            }
            connection.InsertOrUpdate(postViewModel.Post);
            if (postViewModel.Source == "share this")
            {
                var connectFD = new RepositoryBaseMongo("FeedSourceDetail");
                var feedDetail = new FeedSourceDetail();
                feedDetail.UserPostId = Id;
                feedDetail.Body = postViewModel.FeedSourceDetail.Body;
                feedDetail.Title = postViewModel.FeedSourceDetail.Title;
                var path = AppDomain.CurrentDomain.BaseDirectory + "Content\\UserProfile\\PostShareImage\\";

                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                var imagepath = AppDomain.CurrentDomain.BaseDirectory + "Content\\UserProfile\\PostShareImage\\" + UtilityService.RemoveSpecialCharacters(postViewModel.FeedSourceDetail.Title) + ".jpg";
                bool result = UtilityService.DownloadImageFromUrl(postViewModel.FeedSourceDetail.ImageUrl, imagepath);
                if (result)
                {
                    feedDetail.ImageUrl = UtilityService.RemoveSpecialCharacters(postViewModel.FeedSourceDetail.Title) + ".jpg";

                }
                feedDetail.Embed = postViewModel.FeedSourceDetail.Embed;
                connectFD.InsertOrUpdate(feedDetail);

            }
            var ret = new
            {
                Message = postViewModel.Post.Message,
                PostedBy = postViewModel.Post.PostedBy,
                PostedByName = UtilityService.GetCurrentUserFullName(postViewModel.Post.PostedBy),
                PostedByAvatar = "/Content/UserProfile/User/" + UtilityService.GetCurrentUserImage(postViewModel.Post.PostedBy),
                PostedDate = postViewModel.Post.PostedDate,
                PostId = postViewModel.Post.PostId,
                LikeCount = 0,
                StatusHeader = postViewModel.Source,
                LinkThumbnailUrl = postViewModel.Source == "share this" ? postViewModel.FeedSourceDetail.Embed : "",
            };
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ret);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = postViewModel.Post.PostId }));
            return response;
        }

        //public HttpResponseMessage PostPost(PostViewModel postViewModel)
        //{
        //    return null;
        //}
    }

}